package com.etc.service;

import com.etc.dao.IListingP;
import com.etc.entity.Attribute;
import com.etc.dto.ReGoods;
import com.etc.entity.AttributeValue;
import com.etc.entity.CategoryListing;
import com.etc.entity.GoodsSku;
import com.etc.entity.PageImg;
import com.etc.vo.AddAttrVo;
import com.etc.vo.ListingData;
import com.etc.vo.ListingImgVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class ListingProService {
    @Resource
    IListingP listingP;

    /**
     * 查商品类型
     * @return 所有商品类型
     */
    public List<CategoryListing> queryAllCetegory(){
        return listingP.queryAll();
    }

    /**
     * 根据商品类型查属性
     * @param type 商品类型
     * @return 属性组
     */
    public List<Attribute> queryAttrByTyppe(int type){
//        CategoryListing category=parentCheck(type);
//        int t=category.getParent_id()==0?category.getCid():category.getParent_id();
        return parentCheck(type);
    }

    /**
     * 根据属性ID查属性值
     * @param attrId 属性ID
     * @return 属性值组
     */
    public List<AttributeValue> queryAttrValueByAttId(int attrId){
        return listingP.queryAttrValueByType(attrId);
    }

    /**
     *根据当前类目查一级类目
     * @param type 当前类目
     * @return 类目
     */
    public List<Attribute> parentCheck(int type){
        List<Attribute> attrlist=new ArrayList<>();
        attrlist=listingP.queryAttrByType(type);
        CategoryListing category=listingP.queryParent(type);
        if(category.getParent_id()!=0){
            attrlist.addAll(parentCheck(category.getParent_id()));
        }
        return attrlist;
    }

    /**
     * 上架商品（数据库添加）
     */
    @Transactional
    public void listingProData(MultipartFile[] PImg, MultipartFile[] PHtmlImg,ListingData goods, HttpServletRequest request) throws Exception{
        if(listingP.addGoods(goods)==0){
            int i=1/0;
        }
        System.out.println(goods.getGoodsId());
        addGoodsSku(goods);
        ImgToVo(PImg,PHtmlImg,goods);
        listingP.addPageImg(goods.getImg());
        try {
            uploadImg(goods, request);
        } catch (Exception e) {
            int i=1/0;
        }
    }

    /**
     * 上传图片
     * @param goods
     * @param request
     * @throws Exception
     */
    private void uploadImg(ListingData goods, HttpServletRequest request) throws Exception {
        //上传图片
        String rePath= request.getServletContext().getRealPath("/")+"img/"+goods.getGoodsId();
        File file=new File(rePath);
        if(!file.exists()){// 当路径不存在的时候
            file.mkdirs();//  创建文件夹
        }
        String path=request.getServletContext().getRealPath("/")+"img";
        for (int i = 0; i < goods.getImg().size(); i++) {
            File newFile   = new File(path+"/"+ goods.getImg().get(i).getImg_url());
            goods.getImg().get(i).getImg().transferTo(newFile);
        }
    }

    //添加商品SKU
    private void addGoodsSku(ListingData goods)throws Exception {
        String[] tags= goods.getTag();
        Map<String,String[]> tagMap= goods.getTagValMapVal();
        List<String> skuList=new ArrayList<>();
        combo(tagMap.get(tags[0]),0,tags,tagMap,"",skuList);
        Map<String,String[]> tagNameMap= goods.getTagValMapName();
        List<String> skuvalNameList=new ArrayList<>();
        comboName(tagNameMap.get(tags[0]),0,tags,tagNameMap,"",skuvalNameList);
        List<GoodsSku> goodsSkus=new ArrayList<>();
        for (int i = 0; i < skuList.size(); i++) {
            GoodsSku goodsSku=new GoodsSku();
            goodsSku.setGoodsID(goods.getGoodsId());
            goodsSku.setPric(goods.getPrice());
            goodsSku.setSku_properties(skuList.get(i));
            goodsSku.setSku_name(goods.getGoodsName()+skuvalNameList.get(i));
            goodsSkus.add(goodsSku);
        }
        listingP.addSku(goodsSkus);
    }
    //商品SKU生成
    public void combo(String[] s, int index, String[] tags, Map<String,String[]> tagMap,String tmp,List<String> list){
        for (int i = 0; i < s.length; i++) {
            String sku;
            if(index!=0){
                sku=tmp+","+tags[index]+":"+s[i];
            }else{
                sku=tags[index]+":"+s[i];
            }
            if(index<tags.length-1){
                combo(tagMap.get(tags[index+1]),index+1,tags,tagMap,sku,list);
            }else {
                list.add(sku);
            }
        }
    }
    public void comboName(String[] s, int index, String[] tags, Map<String,String[]> tagMap,String tmp,List<String> list){
        for (int i = 0; i < s.length; i++) {
            String sku;
            if(index!=0){
                sku=tmp+s[i];
            }else{
                sku=s[i];
            }
            if(index<tags.length-1){
                comboName(tagMap.get(tags[index+1]),index+1,tags,tagMap,sku,list);
            }else {
                list.add(sku);
            }
        }
    }

    private void ImgToVo(MultipartFile[] PImg, MultipartFile[] PHtmlImg, ListingData goods) {
        List<ListingImgVo> imgVos=new ArrayList<>();
        for (int i = 0; i < PImg.length; i++) {
            if(PImg[i].getOriginalFilename()!=""){
                ListingImgVo imgVo=new ListingImgVo();
                imgVo.setGoods_id(goods.getGoodsId());
                imgVo.setImg_classify(0);
                imgVo.setImg_url(goods.getGoodsId()+"/"+ UUID.randomUUID()+ PImg[i].getOriginalFilename());
                imgVo.setImg(PImg[i]);
                imgVos.add(imgVo);
            }
        }
        for (int i = 0; i < PHtmlImg.length; i++) {
            if(PHtmlImg[i].getOriginalFilename()!=""){
                ListingImgVo imgVo=new ListingImgVo();
                imgVo.setGoods_id(goods.getGoodsId());
                imgVo.setImg_classify(1);
                imgVo.setImg_url(goods.getGoodsId()+"/"+UUID.randomUUID()+ PHtmlImg[i].getOriginalFilename());
                imgVo.setImg(PHtmlImg[i]);
                imgVos.add(imgVo);
            }}
        goods.setImg(imgVos);
    }

//======================================================================//
//======================================================================//
//=============================修改商品===================================//
//======================================================================//
    @Transactional
    //删除图片
    public boolean delImg(int imgId, HttpServletRequest request) throws Exception{
        String path=request.getServletContext().getRealPath("/") + "img/";
        path+=listingP.queryImgUrl(imgId);
        if(listingP.delOneImg(imgId)){
            File file = new File(path);
            if(file.exists()){
                if(file.isFile()){
                    if(!file.delete()){
                        int i=1/0;
                    }
                }
            }return true;
        }else{
            return false;
        }

    }

    /**
     * 添加单一图片
     * @param imgVo 图片
     * @param request 服务访问
     * @return 图片信息
     * @throws Exception 添加异常回滚
     */
    @Transactional
    public ListingImgVo addImg(ListingImgVo imgVo, HttpServletRequest request) throws Exception{
        listingP.addOneImg(imgVo);
        String rePath= request.getServletContext().getRealPath("/")+"img/"+imgVo.getGoods_id();
        File file=new File(rePath);
        if(!file.exists()){// 当路径不存在的时候
            int i=1/0;//  创建文件夹
        }else {
            String path=request.getServletContext().getRealPath("/")+"img";
            File newFile   = new File(path+"/"+imgVo.getImg_url());
            try {
                imgVo.getImg().transferTo(newFile);
            } catch (IOException e) {
                int i=1/0;
            }
        }
        return imgVo;
    }
    public ReGoods queryGoods(int goodsId){
        return  listingP.queryGoods(goodsId);
    }

    /**
     * 修改商品主要属性
     * @param goods 商品
     */
    @Transactional
    public boolean modify(ListingData goods,String oldName) throws Exception{
        if(!("".equals(goods.getGoodsName())) && goods.getGoodsName()!=null){
            if(listingP.modifyGoods(goods)){
                if(listingP.modifySkuNameOnGoodsName(oldName,goods.getGoodsName(), goods.getGoodsId())){
                    return true;
                }else{
                    int i=1/0;
                }
            }
        }
        return false;
    }

    /**
     * 查商品所有图片
     * @param goodsId 商品ID
     */
    public List<PageImg> queryImgByGoodsId(int goodsId){
        return listingP.queryImgByGoodsId(goodsId);
    }

    /**
     * 查看商品Sku
     * @param goodsId
     * @return
     */
    public List<GoodsSku> querySkuByGoodsId(int goodsId){
        return listingP.querySku(goodsId,null);
    }

    public boolean modifySku(GoodsSku sku){
        return listingP.modifySku(sku);
    }
    public boolean delSku(int skuid){
        return listingP.delSKU(skuid);
    }

    public boolean addOneSku(GoodsSku sku){
        List<GoodsSku> goodsSkus=new ArrayList<>();
        goodsSkus.add(sku);
        if(listingP.querySku(sku.getGoodsID(),sku.getSku_properties()).size()>0){
            return false;
        }
        return listingP.addSku(goodsSkus);
    }
    @Transactional
    public boolean addTag(AddAttrVo attrVo) throws Exception{
        Integer attrNID=listingP.queryAttrByTypeAndAttrName(attrVo);
        if(attrNID!=null){
            attrVo.setAttr_name_id(attrNID);
        }else{
            if(!listingP.addAttrName(attrVo)){int i=1/0;}
        }
        for (int i = 0; i < attrVo.getAttr_value().length; i++) {
            if(listingP.addAttrVal(attrVo.getAttr_name_id(),attrVo.getAttr_value()[i])){

            }else{
                int j=1/0;
            }
        }
        return true;
    }
}
